package com.fy.proj3_deepseek_api.config;

import com.fy.proj3_deepseek_api.model.Role;
import com.fy.proj3_deepseek_api.model.User;
import com.fy.proj3_deepseek_api.repository.RoleRepository;
import com.fy.proj3_deepseek_api.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

@Component
public class DataInitializer implements CommandLineRunner {
    @Autowired
    RoleRepository roleRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public void run(String... args) {
        // 创建默认角色
        createDefaultRoles();
        // 创建默认管理员用户
        createDefaultAdminUser();
        // 创建预设普通用户账号
        createPresetUserAccount();
    }

    private void createDefaultRoles() {
        if (!roleRepository.findByName("ROLE_USER").isPresent()) {
            Role userRole = new Role();
            userRole.setName("ROLE_USER");
            roleRepository.save(userRole);
        }

        if (!roleRepository.findByName("ROLE_ADMIN").isPresent()) {
            Role adminRole = new Role();
            adminRole.setName("ROLE_ADMIN");
            roleRepository.save(adminRole);
        }
    }

    private void createDefaultAdminUser() {
        if (!userRepository.findByUsername("admin").isPresent()) {
            User admin = new User();
            admin.setUsername("admin");
            admin.setEmail("admin@example.com");
            admin.setPhone("13800138000");
            admin.setPassword(passwordEncoder.encode("admin123"));
            admin.setEnabled(true);

            Set<Role> roles = new HashSet<>();
            Optional<Role> userRole = roleRepository.findByName("ROLE_USER");
            Optional<Role> adminRole = roleRepository.findByName("ROLE_ADMIN");
            
            userRole.ifPresent(roles::add);
            adminRole.ifPresent(roles::add);
            
            admin.setRoles(roles);
            userRepository.save(admin);
        }
    }
    
    private void createPresetUserAccount() {
        if (!userRepository.findByUsername("user").isPresent()) {
            User user = new User();
            user.setUsername("user");
            user.setEmail("user@example.com");
            user.setPhone("13800138001");
            user.setPassword(passwordEncoder.encode("user123"));
            user.setEnabled(true);

            Set<Role> roles = new HashSet<>();
            Optional<Role> userRole = roleRepository.findByName("ROLE_USER");
            userRole.ifPresent(roles::add);
            
            user.setRoles(roles);
            userRepository.save(user);
        }
    }
}